package com.snail.snailvr.disk.dropbox;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dropbox.core.v2.files.FileMetadata;
import com.dropbox.core.v2.files.FolderMetadata;
import com.dropbox.core.v2.files.Metadata;
import com.snail.snailvr.R;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.Extensions;
import com.snail.snailvr.utils.FileUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.utils.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.ButterKnife;
import rx.Observable;
import rx.SingleSubscriber;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Adapter for file list
 */
public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.MetadataViewHolder> {

    private List<Metadata> mFiles;

    private final Callback mCallback;

    Context context;

    // 过滤掉不需要的数据
    public void setFiles(List<Metadata> files) {

        mFiles.clear();

        for (Metadata file : files)
        {
            if( file instanceof FolderMetadata || Extensions.isVideo(file.getName()))
            {
                mFiles.add(file);
            }
        }

        notifyDataSetChanged();
    }

    public interface Callback {
        void onFolderClicked(FolderMetadata folder);
        void onFileClicked(FileMetadata file);
    }

    public FilesAdapter(Callback callback) {
        mCallback = callback;
        mFiles = new ArrayList<>();
    }

    public List<Metadata> getmFiles() {
        return mFiles;
    }

    @Override
    public MetadataViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        context = viewGroup.getContext();

        View view = LayoutInflater.from(context).inflate(R.layout.net_disk_files_item, viewGroup, false);

        return new MetadataViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MetadataViewHolder metadataViewHolder, int i) {
        metadataViewHolder.bind(mFiles.get(i));
    }

    @Override
    public long getItemId(int position) {
        return mFiles.get(position).getPathLower().hashCode();
    }

    @Override
    public int getItemCount() {
        return mFiles == null ? 0 : mFiles.size();
    }

    public class MetadataViewHolder extends RecyclerView.ViewHolder
    {
        // File
        private final TextView file_name;
        private final ImageView file_image;
        private final ImageView downloadView;

        private final TextView size;
        private final TextView saved;

        private final View filePanel;

        // Folder
        private TextView folder_name;
        private View folderPanel;

        private Metadata mItem;

        public MetadataViewHolder(View itemView) {
            super(itemView);

            file_image = (ImageView)itemView.findViewById(R.id.file_image);
            file_name = (TextView)itemView.findViewById(R.id.file_name);
            downloadView = (ImageView)itemView.findViewById(R.id.file_download);
            size = (TextView)itemView.findViewById(R.id.file_size);
            saved = (TextView)itemView.findViewById(R.id.file_saved);
            filePanel = itemView.findViewById(R.id.filePanel);

            folder_name = (TextView)itemView.findViewById(R.id.folder_name);
            folderPanel = itemView.findViewById(R.id.folderPanel);

            ButterKnife.bind(this, itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mItem instanceof FolderMetadata) {
                        mCallback.onFolderClicked((FolderMetadata) mItem);
                    }
                }
            });

            downloadView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mItem instanceof FileMetadata) {
                        // 开始下载
                        preDownloadFile((FileMetadata) mItem, (ImageView)view);
                    }
                }
            });
        }

        public void bind(final Metadata item) {

            mItem = item;// 判断之外

            if (item instanceof FileMetadata) {//文件

                filePanel.setVisibility(View.VISIBLE);
                folderPanel.setVisibility(View.GONE);

                file_name.setText(item.getName());
                size.setText(FileUtil.formatShortFileSize(context, ((FileMetadata) item).getSize()));

                File dir = DownloadManager.createDownloadDirIfNotExist();
                File target = new File(dir, item.getName());
                if(target.exists()) {
                    saved.setVisibility(View.VISIBLE);
                }
                else {
                    saved.setVisibility(View.GONE);
                }

            }
            else if (item instanceof FolderMetadata)
            {
                folderPanel.setVisibility(View.VISIBLE);
                filePanel.setVisibility(View.GONE);

                folder_name.setText(item.getName());
            }
        }

        private void preDownloadFile(final FileMetadata file, final ImageView hintView) {
            File dir = DownloadManager.createDownloadDirIfNotExist();
            File target = new File(dir, file.getName());

            if ( target.exists() ){// 文件已经存在
                DialogUtils.showBasicDialog((Activity) context, context.getResources().getString(R.string.video_added),
                        context.getResources().getString(R.string.download_again), context.getResources().getString(R.string.cancel),
                        context.getResources().getString(R.string.DOWNLOAD), false, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                hintView.setImageResource(R.drawable.downloading);
                                ((AnimationDrawable) hintView.getDrawable()).start();

                                downloadFile(file, hintView, true);
                            }
                        });
            }
            else{// 文件不存在

                // 下载前开启动画
                hintView.setImageResource(R.drawable.downloading);
                ((AnimationDrawable) hintView.getDrawable()).start();

                downloadFile(file, hintView, false);
            }
        }

        private void downloadFile(final FileMetadata file, final ImageView hintView, final boolean fileExist) {
            // 给出提示
            ToastUtils.makeToastColorShow(context, filePanel, context.getResources().getString(R.string.downloading));

            // 处理索引
            DatabaseUtils.getFileIndex(file.getName(), new SingleSubscriber() {
                @Override
                public void onSuccess(Object value) {
                    String new_name = "";

                    int current_file_index = (int) value;

                    if (current_file_index == -1) {
                        // 无记录，第一次下载，不需要重命名
                        current_file_index++;
                        new_name = file.getName();
                    }
                    else {
                        // 有记录
                        if (fileExist) {
                            current_file_index++;
                            new_name = Util.getRepeatFileName(file.getName(), current_file_index);
                        }
                        else{
                            // 数据库有文件记录，但实际文件被删除
                            // 不需要重命名
                            new_name = file.getName();
                        }
                    }

                    // 开始下载后,将记录保存到数据库
                    DatabaseUtils.saveFileIndex(file.getName(), current_file_index);

                    new DownloadFileTask(context, DropboxClientFactory.getClient(), new DownloadFileTask.Callback() {
                        @Override
                        public void onDownloadComplete(final File result) {
                            if (result != null) {
                                // 更新UI

                                hintView.setAlpha(0.0f);
                                hintView.setImageResource(R.drawable.ic_net_disk_download_finish);
                                hintView.animate().alpha(1.0f).setDuration(Constant.NETDISK_ANIM_DURATION).start();

                                Observable.timer(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Long>() {
                                    @Override
                                    public void onCompleted() {
                                        // 更新UI

                                        hintView.setAlpha(0.0f);
                                        hintView.setImageResource(R.drawable.ic_net_disk_download_normal);
                                        hintView.animate().alpha(1.0f).setDuration(Constant.NETDISK_ANIM_DURATION).start();
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                    }

                                    @Override
                                    public void onNext(Long aLong) {
                                    }
                                });

                                if(saved.getVisibility() == View.GONE){
                                    saved.setVisibility(View.VISIBLE);
                                }

                                DownloadHelper.addNewTransferVideoTask(result.getName(), result.getPath());
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            ToastUtils.makeToastColorShow(context, filePanel, context.getString(R.string.error_occurred));

                            hintView.setAlpha(0.0f);
                            hintView.setImageResource(R.drawable.ic_net_disk_download_normal);
                            hintView.animate().alpha(1.0f).setDuration(Constant.NETDISK_ANIM_DURATION).start();
                        }
                    }, new_name).execute(file);

                }

                @Override
                public void onError(Throwable error) {
                    hintView.setAlpha(0.0f);
                    hintView.setImageResource(R.drawable.ic_net_disk_download_normal);
                    hintView.animate().alpha(1.0f).setDuration(Constant.NETDISK_ANIM_DURATION).start();
                }
            });
        }
    }
}
